<template>
  <div class="wrapper">
    <div class="header custom-input-wrapper">
      <a-form-model layout="inline" :model="searchForm" @submit="handleSubmit" @submit.native.prevent>
        <a-form-model-item label="任务名称">
          <a-input class="custom-input" v-model="searchForm.name" placeholder="输入任务名称" />
        </a-form-model-item>
        <a-form-model-item label="任务类型">
          <a-select
            class="custom-select"
            v-model="searchForm.taskType"
            placeholder="请选择任务类型"
            style="width: 180px"
            allowClear
          >
            <a-select-option value="inference">推理</a-select-option>
            <a-select-option value="validation">验证</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item>
          <a-button class="border-radius-4" type="primary" icon="search" @click="handleSearch">搜索</a-button>
        </a-form-model-item>
      </a-form-model>
    </div>
    <div class="body">
      <a-button class="operateButtons" type="primary" icon="plus" @click="showAddModal"> 新建任务 </a-button>
      <a-table :columns="columns" size="middle" :data-source="data" class="custom-table">
        <template slot="labels" slot-scope="labels">
          <template v-if="labels">
            <a-tag v-for="label in labels.split(', ')" :key="label">
              {{ label }}
            </a-tag>
          </template>
        </template>
        <span slot="action" slot-scope="text, record, index">
          <a-button type="link" class="px-0" @click="handleRun(record)">运行</a-button>
          <a-divider type="vertical" />
          <a-button type="link" class="px-0" :disabled="!record.lastRunResult" @click="handleViewResult(record)">
            查看结果
          </a-button>
          <a-divider type="vertical" />
          <a-button type="link" class="px-0" @click="handleDelete(record)"> 删除 </a-button>
        </span>
      </a-table>
    </div>
    <div class="footer"></div>
    <edit ref="edit" @success="handleSuccess" />
    <result ref="result" />
  </div>
</template>

<script>
import { listTask, runTask, deleteTask } from '../../../api/model'
import { formatTime } from '../../../utils/util'
import notification from 'ant-design-vue/es/notification'
import edit from './editMission'
import result from './result'
const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    align: 'center',
    width: 80,
    customRender: (text, record, index) => `${index + 1}`,
  },
  {
    title: '任务名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '任务类型', // 新增任务类型列
    dataIndex: 'taskType',
    key: 'taskType',
    customRender: (text) => {
      const typeMap = {
        inference: '推理',
        validation: '验证',
      }
      return typeMap[text] || text
    },
  },
  {
    title: '模型', // 新增模型列
    dataIndex: 'modelName',
    key: 'modelName',
  },
  // {
  //   title: '数据源', // 新增数据源列
  //   dataIndex: 'dataSource',
  //   key: 'dataSource',
  // },
  // {
  //   title: '状态',
  //   dataIndex: 'status',
  //   key: 'status',
  // },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    customRender: (text) => {
      if (!text) return '-'
      return new Date(text).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false,
      })
    },
  },
  {
    title: '操作',
    key: 'action',
    width: 180, // 设置序号列的宽度
    scopedSlots: { customRender: 'action' },
  },
]
export default {
  name: 'Assessment',
  components: {
    edit,
    result,
  },
  data() {
    return {
      data: [],
      originalData: [], // 添加originalData数组
      formInline: {
        user: '',
        password: '',
      },
      columns,
      visible: false,
      isEdit: false,
      modalTile: '新增',
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
      form: {
        name: '',
        labels: undefined,
        indicator: undefined,
        savePath: '',
      },

      addModalTitle: '新增模型',
      addVisible: false,
      addForm: {
        name: '',
      },
      searchForm: {
        name: '',
        taskType: undefined,
      },
      labelOptions: [
        { label: '标签1', value: 'tag-1' },
        { label: '标签2', value: 'tag-2' },
      ],
    }
  },
  methods: {
    generateRandomId() {
      const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
      let id = ''
      for (let i = 0; i < 4; i++) {
        const randomIndex = Math.floor(Math.random() * chars.length)
        id += chars[randomIndex]
      }
      return id
    },
    getCurrentTime() {
      const now = new Date()

      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0') // 月份从0开始，因此+1
      const day = String(now.getDate()).padStart(2, '0')

      const hours = String(now.getHours()).padStart(2, '0')
      const minutes = String(now.getMinutes()).padStart(2, '0')
      const seconds = String(now.getSeconds()).padStart(2, '0')

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    handleSubmit(e) {
      console.log(this.formInline)
    },
    showAddModal() {
      this.$refs.edit.showModal()
    },
    handleOk(e) {
      console.log(this.form)
      this.data = [{ ...this.form, modalId: this.generateRandomId(), createTime: this.getCurrentTime() }, ...this.data]
      this.visible = false
      this.handleReset()
    },
    handleCancel() {
      this.visible = false
      this.handleReset()
    },
    handleReset() {
      this.form = {
        name: '',
        labels: '',
        indicator: '',
        savePath: '',
      }
    },
    handleEdit(row) {
      this.isEdit = true
      this.form = {
        ...row,
      }
      // this.showAddModal()
    },
    handleDelete(record) {
      this.$confirm({
        title: '确认删除',
        content: `确定要删除任务"${record.name}"吗？`,
        okText: '确认',
        cancelText: '取消',
        onOk: async () => {
          try {
            await deleteTask({ taskName: record.name })
            await this.getData()
            this.$message.success('删除成功')
          } catch (error) {
            this.$message.error(`删除失败：${error.message || '未知错误'}`)
          }
        },
      })
    },
    handleSearch() {
      // 如果搜索条件都为空,显示所有数据
      if (!this.searchForm.name && !this.searchForm.taskType) {
        this.data = [...this.originalData]
        return
      }

      // 本地过滤数据
      this.data = this.originalData.filter((item) => {
        const nameMatch = !this.searchForm.name || item.name.toLowerCase().includes(this.searchForm.name.toLowerCase())
        const typeMatch = !this.searchForm.taskType || item.taskType === this.searchForm.taskType
        return nameMatch && typeMatch
      })
    },
    onSubmit() {
      console.log('submit!', this.form)
    },
    async getData() {
      try {
        const response = await listTask()
        this.data = response || []
        this.originalData = [...this.data] // 保存一份原始数据用于搜索
      } catch (error) {
        // this.$message.error('获取任务列表失败：' + (error.message || '未知错误'))
        // console.error('获取任务列表失败:', error)
      }
    },
    handleSuccess() {
      this.getData() // 刷新表格数据
    },
    handleAddOk(e) {
      console.log(e)
      const newThis = this
      addModel(newThis.addForm)
        .then((result) => {
          newThis.addVisible = false
          newThis.pageModels()
          notification.success({
            message: '新增成功',
            description: `新增成功`,
          })
        })
        .catch((error) => {
          newThis.addVisible = false
          notification.error({
            message: '新增失败',
            description: `新增失败`,
          })
        })
    },
    handleAddCancel() {
      this.addVisible = false
    },
    handleGetInfo(record) {
      this.$refs.detail.showModal(record)
    },
    handleViewResult(record) {
      // TODO: 根据实际需求实现查看结果的逻辑
      this.$message.info(`查看任务"${record.name}"的结果`)
    },
    handleRun(record) {
      this.$confirm({
        title: '确认运行',
        content: `确定要运行任务"${record.name}"吗？`,
        okText: '确认',
        cancelText: '取消',
        onOk: async () => {
          try {
            await runTask({ taskName: record.name })
            this.$message.success(`任务"${record.name}"已开始运行`)
          } catch (error) {
            this.$message.error(`运行失败：${error.message || '未知错误'}`)
          }
        },
      })
    },
    handleViewResult(record) {
      this.$refs.result.showModal(record)
    },
  },
  mounted() {
    this.getData()
  },
}
</script>

<style lang="less" scoped>
@import '../index.less';
</style>
